package com.kd.juhaowan.ui;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;


import com.google.android.material.tabs.TabLayout;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.hjq.toast.ToastUtils;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.AutoLoginApi;
import com.kd.juhaowan.http.api.CheckVersionApi;
import com.kd.juhaowan.http.api.CommonApi;
import com.kd.juhaowan.http.model.ActivityModel;
import com.kd.juhaowan.http.model.CateModel;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.HttpListData;
import com.kd.juhaowan.http.model.VersionModel;
import com.kd.juhaowan.model.LoginUser;
import com.kd.juhaowan.ui.adapter.CommonFragmentPagerAdapter;
import com.kd.juhaowan.ui.fragment.FuliFragment;
import com.kd.juhaowan.ui.fragment.GameFragment;
import com.kd.juhaowan.ui.fragment.HomeFragmentNew;
import com.kd.juhaowan.ui.fragment.MineFragment;
import com.kd.juhaowan.utils.DeviceUtil;
import com.kd.juhaowan.utils.LogUtil;
import com.kd.juhaowan.view.CustomTabView;
import com.kd.juhaowan.view.NoScrollViewPager;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import okhttp3.Call;

public class MainActivity extends BaseActivity {


    @BindView(R.id.main_activity_tabLayout)
    TabLayout mMainTabLayout;
    @BindView(R.id.main_activity_viewpager)
    NoScrollViewPager mMainViewPager;

    @BindArray(R.array.mall_main_activity_tab_text)
    String[] mMainTabText;

    int[] mMainTabIconResourceId = new int[]{
            R.drawable.tab_home_selecter,
            R.drawable.tab_game_selecter,
//            R.drawable.tab_fuli_selecter,
            R.drawable.tab_mine_selecter};

    private VersionModel versionModel;
    private ActivityModel activityModel;
    ActivityResultLauncher<Intent> updateLauncher,activityLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainViewPager.setOffscreenPageLimit(0);

        EasyHttp.post(this).api(new CommonApi("api/game/CatList")).request(new HttpCallbackProxy<HttpListData<CateModel>>(this){
            @Override
            public void onHttpSuccess(HttpListData<CateModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                result.getData().getList();
                manager.saveCatelist(result.getData().getList());
                initFragmentTab();
            }
        });

        EasyHttp.post(this).api(new CheckVersionApi()).request(new HttpCallbackProxy<HttpData<VersionModel>>(this){
            @Override
            public void onHttpSuccess(HttpData<VersionModel> result, boolean cache) {
                versionModel = result.getData();

                super.onHttpSuccess(result, cache);
                try {
                    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                    String versionName = packageInfo.versionName;
//                    if(DeviceUtil.isVersionNewer(versionName,versionModel.getNewversion())&& !FileDownloadUtils.isNetworkNotOnWifiType()){
                    if(DeviceUtil.isVersionNewer(versionName,versionModel.getNewversion())){
//                        startDownload();
                        Intent intent = new Intent(MainActivity.this,VersionUpdateActivity.class);
                        intent.putExtra("model",versionModel);
                        updateLauncher.launch(intent);
                    }else{
                        LogUtil.debugLog("isnewestVersion");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

//            @Override
//            public void onHttpFail(Exception e) {
//                super.onHttpFail(e);
//                versionModel = new VersionModel();
//                versionModel.setNewversion("2.0");
//                versionModel.setContent("dfajfja j;a; ;dfa;fjafja");
//                versionModel.setDownloadfile("https://download.doglab.cn/doglab/apk/kd_flj_1206.apk");
//                try {
//                    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
//                    String versionName = packageInfo.versionName;
////                    if(DeviceUtil.isVersionNewer(versionName,versionModel.getNewversion())&& !FileDownloadUtils.isNetworkNotOnWifiType()){
//                    if(DeviceUtil.isVersionNewer(versionName,versionModel.getNewversion())){
////                        startDownload();
//                        Intent intent = new Intent(MainActivity.this,VersionUpdateActivity.class);
//                        intent.putExtra("model",versionModel);
//                        updateLauncher.launch(intent);
//                    }else{
//                        LogUtil.debugLog("isnewestVersion");
//                    }
//                }catch (Exception e2){
//                    e2.printStackTrace();
//                }
//            }
        });

        EasyHttp.post(this).api(new CommonApi("api/popup")).request(new HttpCallbackProxy<HttpData<ActivityModel>>(this){
            @Override
            public void onHttpSuccess(HttpData<ActivityModel> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                activityModel = result.getData();
                if(activityModel!=null&& !TextUtils.isEmpty(activityModel.getId())){
                    Intent in = new Intent(MainActivity.this,ActivityActivity.class);
                    in.putExtra("model",activityModel);
                    activityLauncher.launch(in);

                }
            }


        });

        updateLauncher =registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        int resultCode = result.getResultCode();
                        if (resultCode == RESULT_OK) {
//                            startVersionInstallTask();
                        } else if (resultCode == RESULT_CANCELED) {
                            Log.i("adb", "onActivityResult PictureSelector Cancel");
                        }
                    }
                });
        activityLauncher =registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        int resultCode = result.getResultCode();
                        if (resultCode == RESULT_OK) {
                            if(activityModel.getJump_type()==0){
                                try {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(activityModel.getJump_value())));
                                } catch (ActivityNotFoundException exception) {
                                    exception.printStackTrace();
                                    Toast.makeText(getApplicationContext(), "浏览器打开异常", Toast.LENGTH_SHORT).show();

                                }
                            }else if (activityModel.getJump_type()==1){
                                Intent in = new Intent(MainActivity.this,GameDetailActivity.class);
                                in.putExtra("id",activityModel.getJump_value());
                                startActivity(in);
                            }else if (activityModel.getJump_type()==2){
                                Intent in = new Intent(MainActivity.this,DocumentActivity.class);
                                in.putExtra("shequ_id",activityModel.getJump_value());
                                startActivity(in);

                            }
                        } else if (resultCode == RESULT_CANCELED) {
                            Log.i("adb", "onActivityResult PictureSelector Cancel");
                        }
                    }
                });
        refreshToken();
    }


    private void refreshToken(){
        List<LoginUser> infos = manager.readAllUserAccountInfo();
        LogUtil.debugLog("refreshToken"+(manager.readAutoLogin()&&infos.size()>0));
        if(manager.readAutoLogin()&&infos.size()>0){
            LoginUser user = infos.get(0);
            EasyHttp.post(this).api(new AutoLoginApi(user.getRefresh_token()+"...")).request(new HttpCallbackProxy<HttpData<LoginUser>>(this){
                @Override
                public void onHttpSuccess(HttpData<LoginUser> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    LoginUser loginUser = result.getData();
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    user.setAccess_token(loginUser.getAccess_token());
                    user.setRefresh_token(loginUser.getRefresh_token());
                    manager.saveUserAccount(user);
                    manager.writeAutoLogin(true);
                    manager.writeLastLoginType(1);
                    manager.saveCurrentLoginUserTickit(user.getAccess_token());

                }

                @Override
                public void onHttpEnd(Call call) {
                    super.onHttpEnd(call);

                }
            });
        }

    }



//    private File loadFile;

    @Override
    protected void reInitDate() {

    }


    public void goTip(){

    }
    private  int currentItem=0;
    public int getCurrentItem(){
        return currentItem;
    }


    private final List<Fragment> fragments = new ArrayList<>();
    private HomeFragmentNew homeFragmentNew = new HomeFragmentNew();
    private GameFragment gameFragment = new GameFragment();
    private FuliFragment fuliFragment = new FuliFragment();
    private MineFragment mineFragment = new MineFragment();

    private void initFragmentTab(){
        if (fragments.isEmpty()) {
            fragments.add(homeFragmentNew);
            fragments.add(gameFragment);
//            fragments.add(fuliFragment);
            fragments.add(mineFragment);
        }

        mMainViewPager.setOffscreenPageLimit(fragments.size());
        mMainViewPager.setAdapter(new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        mMainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentItem = tab.getPosition();
                mMainViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                mMainViewPager.setCurrentItem(tab.getPosition());
                currentItem = tab.getPosition();
            }
        });

        mMainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                mMainTabLayout.setScrollPosition(position, 0f, true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        final int tabCount = mMainTabText.length;
        for (int index = 0; index < tabCount; index++) {
            CustomTabView tabView = new CustomTabView(this);
            tabView.setIcon(mMainTabIconResourceId[index]);
            tabView.setText(mMainTabText[index]);
            TabLayout.Tab tab = mMainTabLayout.newTab();
            tab.setCustomView(tabView);
//            tab.setIcon(mMainTabIconResourceId[index]);
//            tab.setText(mMainTabText[index]);
            mMainTabLayout.addTab(tab.setTag(index));
        }
    }

    long exitTime=0;// 退出时间
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // 判断间隔时间 大于2秒就退出应用
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                // 应用名
                String applicationName = getResources().getString(
                        R.string.app_name);
                ToastUtils.show("再按一次返回桌面");

                // 计算两次返回键按下的时间差
                exitTime = System.currentTimeMillis();
            } else {
                // 关闭应用程序
                //finish();
                // 返回桌面操作
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.addCategory(Intent.CATEGORY_HOME);
                startActivity(home);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_main;
    }
}